<template>
    <view class="apply_service_form">
        <view v-if="!sigleSerial" class="form_item">
            <view class="form_item_label"> <text class="must">*</text>序列号 </view>
            <view class="form_item_con" @click="showSerialOption">
                {{ formData.simSerialNumber }}
                <text v-if="!formData.simSerialNumber" style="color: #a9aab5; font-size: 30rpx"
                    >请选择序列号</text
                >
                <image
                    :src="`${OSS_URL}/iconfont/down_arrow.png`"
                    class="more_down"
                    mode=""
                ></image>
            </view>
            <view v-if="isEmpty.serial" class="error">请填写序列号</view>
        </view>
        <view class="form_item">
            <view class="form_item_label"> <text class="must">*</text>问题描述 </view>
            <view class="form_item_problem">
                <textarea
                    v-model="formData.description"
                    class="problem_input"
                    :maxlength="maxlength"
                    placeholder="请详细描述您遇到的问题"
                    placeholder-style="color:#A9AAB5;font-size:30rpx;"
                    @input="handleInputProblem"
                />
                <view class="input_num"
                    ><text>{{ fontNum }}</text
                    >/200</view
                >
            </view>
            <view v-if="isEmpty.description" class="error">请填写问题描述</view>
        </view>
        <view class="form_item">
            <view class="form_item_label image_tip">
                添加您认为可以更好说明问题的图片（最多4张）
            </view>
            <view class="uplaod_problem">
                <view v-if="tempImageUrl.length > 0" class="all_img">
                    <view v-for="(i, idx) in tempImageUrl" :key="idx" class="problem_img">
                        <image
                            :src="i"
                            mode=""
                            class="show_problem"
                            @click="previewImg(idx)"
                        ></image>
                        <image
                            :src="`${OSS_URL}/iconfont/close_icon.png`"
                            mode=""
                            class="close_icon"
                            @click="deleteImg(idx)"
                        ></image>
                    </view>
                </view>
                <image
                    v-if="tempImageUrl.length < 4"
                    :src="`${OSS_URL}/upload_icon.png`"
                    class="upload_icon"
                    mode=""
                    @load="loadUploadIcon"
                    @error="errorUploadIcon"
                    @click="uploadImage"
                >
                </image>
            </view>
        </view>
        <view class="form_item">
            <view class="form_item_label"> <text class="must">*</text>联系方式 </view>
            <input
                v-model="formatPhone"
                class="phone_input"
                type="text"
                placeholder="请留下您的手机号码"
                placeholder-style="color:#A9AAB5;font-size:30rpx;"
                @blur="blurInputPhone"
                @input="phoneDivision"
            />
            <view>
                <text v-if="!isPhoneValid" class="error">手机号错误</text>
                <text v-if="isEmpty.phone" class="error">请填写手机号</text>
            </view>
        </view>
        <view class="footer">
            <button class="btn-primary" @click="submit">提交</button>
        </view>
        <!-- 弹出框选项 -->
        <Picker
            v-model="showPicker"
            :pickVal="pickVal"
            :pickList="pickList"
            title="选择序列号"
            @confirm="confirmPicker"
        />
        <!-- 提交成功提示框 -->
        <TipPopup
            v-model="showTipPopup"
            showBtn
            :showSuccessIcon="false"
            text="提交成功"
            btnText="确定"
            messageTip="7个工作日内会有<br />工作人员同您电话联系，请留意"
            @backBtn="backBtn"
        />
    </view>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { applyServiceApi } from '@/api';

import { uploadFile } from '@/utils';
import Picker from '@/Components/Picker/index.vue';
import TipPopup from '@/Components/TipPopup/index.vue';
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const showTipPopup = ref(false);
const showPicker = ref(false);
const pickVal = ref([0]); // 序列号选中值
const pickList = ref([]); // 序列号列表
const sigleSerial = ref(false); // 是否单张保修卡
const isPhoneValid = ref(true); // 手机号检验
const maxlength = ref(-1);
// 输入内容是否为空
const isEmpty = ref({
    serial: false,
    description: false,
    phone: false,
});
const fontNum = ref(0);
const formatPhone = ref(''); // 格式化手机号
const tempImageUrl = ref([]); // 临时存储图片
const formData = ref({
    description: '',
    imageUrl: '',
    phone: '',
    simSerialNumber: '',
});

function handleInputProblem(event) {
    let value = event.detail.value.replace(/\s+/g, '');
    setTimeout(() => {
        if (value.length >= 200) {
            maxlength.value = 200;
            value = value.substr(0, 200);
        } else {
            maxlength.value = -1;
            value = value.substr(0, value.length);
        }
        event.detail.value = value;
        formData.value.description = value;
        fontNum.value = formData.value.description.length;
        isEmpty.value.description = fontNum.value === 0;
    }, 0);
}
// 序列号
function showSerialOption() {
    showPicker.value = true;
}
// 序列号选择
function confirmPicker(val) {
    if (val) {
        let idx = val[0];
        pickVal.value = [Number(idx)];
        formData.value.simSerialNumber = pickList.value[idx].name;
        formData.value.stuId = pickList.value[idx].smartUserIdentifier;
        isEmpty.value.serial = formData.value.simSerialNumber.length === 0;
    }
    showPicker.value = false;
}
// 上传图标加载完毕
function loadUploadIcon(e) {
    wx.hideLoading();
}

function errorUploadIcon() {
    wx.hideLoading();
}
// 上传图片
function uploadImage() {
    uni.chooseImage({
        count: 4 - tempImageUrl.value.length, // 最多可以选择的图片张数
        sizeType: ['compressed', 'original'], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album', 'camera'],
        // album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
        success: res => {
            // 成功返回的函数
            res.tempFilePaths.map(item => tempImageUrl.value.push(item));
        },
        fail: err => {
            // 图片接口调用失败的回调函数
            console.log('chooseImage fail', err);
        },
    });
}
// 查看图片
function previewImg(idx) {
    uni.previewImage({
        current: idx,
        urls: tempImageUrl.value,
    });
}
// 删除图片
function deleteImg(i) {
    tempImageUrl.value.splice(i, 1);
}
// 手机号检验
function blurInputPhone() {
    if (formatPhone.value) {
        const phoneReg = /^[1][3-9]\d{9}$/;
        const phone = formatPhone.value.replace(/\s+/g, '');
        isPhoneValid.value = phoneReg.test(phone);
    } else {
        isPhoneValid.value = true;
    }
    if (!isPhoneValid.value) {
        isEmpty.value.phone = false;
    } else {
        isEmpty.value.phone = formatPhone.value.length === 0;
    }
}
// 手机344分割
function phoneDivision() {
    nextTick(() => {
        let value = formatPhone.value.replace(/\D/g, '').substr(0, 11);
        let len = value.length; // 获取长度判断
        if (len > 3 && len < 8) {
            value = value.replace(/^(\d{3})/g, '$1 ');
        } else if (len >= 8) {
            value = value.replace(/^(\d{3})(\d{4})/g, '$1 $2 ');
        }
        formatPhone.value = value;
    });
}

// 提交
async function submit() {
    formData.value.phone = formatPhone.value.replace(/\s+/g, '');
    isEmpty.value = {
        serial: !formData.value.simSerialNumber,
        description: !formData.value.description,
        phone: !formData.value.phone,
    };
    if (
        isEmpty.value.serial ||
        isEmpty.value.description ||
        isEmpty.value.phone ||
        !isPhoneValid.value
    )
        return;
    uni.showLoading({
        title: '提交申请中',
    });

    if (tempImageUrl.value.length > 0) {
        let imageUrlList = [];
        console.log('tempImageUrl', tempImageUrl.value);
        for (let i in tempImageUrl.value) {
            const res1 = await uploadFile(tempImageUrl.value[i]);
            imageUrlList.push(res1);
        }
        formData.value.imageUrl = imageUrlList.join(',');
    }
    applyServiceApi(formData.value)
        .then(res => {
            if (res.code === 200) {
                uni.hideLoading();
                showTipPopup.value = true;
            }
        })
        .catch(err => {
            uni.hideLoading();
        });
}

function backBtn() {
    uni.navigateBack({
        delta: 1, // 默认值是1，表示返回的页面层数
    });
}
onLoad(option => {
    uni.showLoading({
        title: '加载中',
    });
    let warrantyList = JSON.parse(option.simList);
    warrantyList.map((item, idx) =>
        pickList.value.push({
            name: item.simSerialNumber,
            smartUserIdentifier: item.smartUserIdentifier,
            index: idx,
        }),
    );
    sigleSerial.value = warrantyList.length === 1;
    if (sigleSerial.value) {
        formData.value.simSerialNumber = warrantyList[0].simSerialNumber;
        formData.value.stuId = warrantyList[0].smartUserIdentifier;
    }
});
</script>

<style lang="scss" scoped>
.apply_service_form {
    margin: 30rpx 30rpx 0;
    padding: 30rpx 30rpx 40rpx 30rpx;
    box-sizing: border-box;
    border-radius: 20rpx;
    color: #333;
    background-color: #fff;
    font-size: 30rpx;

    .form_item {
        margin-bottom: 32rpx;

        &_label {
            margin-bottom: 16rpx;
            font-weight: 500;
        }

        &_con {
            position: relative;
            padding: 24rpx 20rpx;
            box-sizing: border-box;
            height: 90rpx;
            background-color: #f9f9fb;
            border-radius: 16rpx;

            .more_down {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                right: 30rpx;
                width: 30rpx;
                height: 30rpx;
            }
        }

        &_problem {
            position: relative;

            .problem_input {
                padding: 30rpx 20rpx 56rpx 20rpx;
                box-sizing: border-box;
            }

            .input_num {
                position: absolute;
                bottom: 18rpx;
                right: 20rpx;
                font-size: 24rpx;
                color: #a9aab5;
            }
        }

        .must {
            color: red;
        }

        .image_tip {
            font-size: 26rpx;
            color: #999;
            white-space: nowrap;
        }

        .uplaod_problem {
            display: flex;
            white-space: nowrap;

            .all_img {
                display: flex;

                .problem_img {
                    position: relative;
                    margin-right: calc((100vw - 540rpx) / 4);
                    width: 120rpx;
                    height: 120rpx;

                    .show_problem {
                        width: 100%;
                        height: 100%;
                    }

                    &:nth-child(4n) {
                        margin-right: 0 !important;
                    }

                    .close_icon {
                        position: absolute;
                        top: 0;
                        right: 0;
                        width: 30rpx;
                        height: 30rpx;
                        background-color: #fff;
                    }
                }
            }

            .upload_icon {
                width: 120rpx;
                height: 120rpx;
            }
        }

        .problem_input {
            width: 100%;
            height: 274rpx;
            background-color: #f9f9fb;
            border-radius: 16rpx;
        }

        .phone_input {
            height: 90rpx;
            padding: 0 20rpx;
            box-sizing: border-box;
            background-color: #f9f9fb;
            border-radius: 16rpx;
        }

        .error {
            margin-top: 16rpx;
            font-size: 26rpx;
            color: #ff3d3d;
        }
    }

    .footer {
        position: absolute;
        display: flex;
        flex-direction: row;
        bottom: 0;
        width: 100%;
        height: 172rpx;
        left: 0;
        box-sizing: border-box;
        background-color: #fff;
        border-top: 1rpx solid #eee;

        button::after {
            border: none;
        }

        .btn-primary {
            margin-top: 16rpx;
            box-sizing: border-box;
            width: 440rpx;
            height: 90rpx;
            background-color: #615dff;
            color: #ffffff;
            border-radius: 20rpx;
            font-size: 30rpx;
            line-height: 90rpx;
        }
    }
}
</style>
